/**
 * 消息模板选择器
 */
import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Modal, List, Typography, Popconfirm, Input, Form, Tabs, Empty, Icon } from 'antd';
import './MessageTemplateSelector.less';

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;
const { TabPane } = Tabs;

@inject('MessageTemplateStore', 'TaskStore', 'CommonStore')
@observer
class MessageTemplateSelector extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isModalVisible: false,
      isEditing: false,
    };
  }

  componentDidMount() {
    this.props.MessageTemplateStore.getMessageTemplates();
  }

  // 打开模板选择器
  showTemplateSelector = () => {
    console.log('showTemplateSelector called');
    this.setState({ isModalVisible: true });
  }

  // 关闭模板选择器
  closeTemplateSelector = () => {
    console.log('closeTemplateSelector called');
    this.setState({ isModalVisible: false, isEditing: false });
    this.props.MessageTemplateStore.resetEditingTemplate();
  }

  // 选择模板
  selectTemplate = (template) => {
    const { TaskStore } = this.props;
    
    // 根据消息类型设置不同的内容
    if (template.msgType === 'text') {
      TaskStore.handleTextChange('publishTextContent', { target: { value: template.content } });
    } else if (template.msgType === 'markdown') {
      TaskStore.handleTextChange('publishMarkdownContent', { target: { value: template.content } });
    }
    
    // 设置消息类型
    TaskStore.handleDropdownChange('msgTypeValue', template.msgType);
    
    // 关闭模态框
    this.closeTemplateSelector();
  }

  // 添加新模板
  addNewTemplate = () => {
    console.log('addNewTemplate called');
    this.setState({ isEditing: true });
    this.props.MessageTemplateStore.resetEditingTemplate();
  }

  // 编辑模板
  editTemplate = (template, e) => {
    e.stopPropagation();
    this.setState({ isEditing: true });
    this.props.MessageTemplateStore.updateEditingTemplate('id', template.id);
    this.props.MessageTemplateStore.updateEditingTemplate('title', template.title);
    this.props.MessageTemplateStore.updateEditingTemplate('content', template.content);
    this.props.MessageTemplateStore.updateEditingTemplate('msgType', template.msgType);
  }

  // 取消编辑
  cancelEdit = () => {
    console.log('cancelEdit called');
    this.setState({ isEditing: false });
    this.props.MessageTemplateStore.resetEditingTemplate();
  }

  // 保存模板
  saveTemplate = () => {
    console.log('saveTemplate called');
    const { MessageTemplateStore, CommonStore } = this.props;
    const { editingTemplate } = MessageTemplateStore;
    
    if (!editingTemplate.title.trim()) {
      CommonStore.alertMessage('error', '标题不能为空');
      return;
    }
    
    if (!editingTemplate.content.trim()) {
      CommonStore.alertMessage('error', '内容不能为空');
      return;
    }
    
    if (editingTemplate.id) {
      // 更新现有模板
      MessageTemplateStore.updateMessageTemplate()
        .then(() => {
          CommonStore.alertMessage('success', '更新成功');
          this.setState({ isEditing: false });
        })
        .catch((err) => {
          CommonStore.alertMessage('error', err || '更新失败');
        });
    } else {
      // 创建新模板
      MessageTemplateStore.createMessageTemplate()
        .then(() => {
          CommonStore.alertMessage('success', '创建成功');
          this.setState({ isEditing: false });
        })
        .catch((err) => {
          CommonStore.alertMessage('error', err || '创建失败');
        });
    }
  }

  // 删除模板
  deleteTemplate = (id, e) => {
    e.stopPropagation();
    this.props.MessageTemplateStore.deleteMessageTemplate(id)
      .then(() => {
        this.props.CommonStore.alertMessage('success', '删除成功');
      })
      .catch((err) => {
        this.props.CommonStore.alertMessage('error', err || '删除失败');
      });
  }

  // 处理输入变化
  handleInputChange = (field, e) => {
    this.props.MessageTemplateStore.updateEditingTemplate(field, e.target.value);
  }

  // 渲染模板列表
  renderTemplateList = () => {
    const { messageTemplates } = this.props.MessageTemplateStore;
    
    if (messageTemplates.length === 0) {
      return <Empty description="暂无消息模板" />;
    }
    
    return (
      <List
        itemLayout="vertical"
        dataSource={messageTemplates}
        renderItem={item => (
          <List.Item
            key={item.id}
            actions={[
              <Button 
                icon="edit" 
                size="small" 
                onClick={(e) => this.editTemplate(item, e)}
              >
                编辑
              </Button>,
              <Popconfirm
                title="确定要删除这个模板吗？"
                onConfirm={(e) => this.deleteTemplate(item.id, e)}
                okText="确定"
                cancelText="取消"
                icon={<Icon type="exclamation-circle" style={{ color: 'red' }} />}
              >
                <Button 
                  icon="delete" 
                  size="small" 
                  type="danger"
                  onClick={(e) => e.stopPropagation()}
                >
                  删除
                </Button>
              </Popconfirm>
            ]}
            onClick={() => this.selectTemplate(item)}
            className="template-item"
          >
            <List.Item.Meta
              title={<Text strong>{item.title}</Text>}
              description={<Text type="secondary">{`类型: ${item.msgType === 'text' ? '文本' : 'Markdown'}`}</Text>}
            />
            <div className="template-content">
              <Paragraph ellipsis={{ rows: 2, expandable: true, symbol: '展开' }}>
                {item.content}
              </Paragraph>
            </div>
          </List.Item>
        )}
      />
    );
  }

  // 渲染编辑表单
  renderEditForm = () => {
    const { editingTemplate } = this.props.MessageTemplateStore;
    
    return (
      <Form layout="vertical">
        <Form.Item label="标题" required>
          <Input 
            value={editingTemplate.title} 
            onChange={(e) => this.handleInputChange('title', e)} 
            placeholder="请输入模板标题"
          />
        </Form.Item>
        <Form.Item label="内容" required>
          <TextArea 
            value={editingTemplate.content} 
            onChange={(e) => this.handleInputChange('content', e)} 
            placeholder="请输入模板内容"
            autoSize={{ minRows: 4, maxRows: 8 }}
          />
        </Form.Item>
        <Form.Item label="消息类型">
          <Tabs 
            activeKey={editingTemplate.msgType} 
            onChange={(value) => this.props.MessageTemplateStore.updateEditingTemplate('msgType', value)}
          >
            <TabPane tab="文本" key="text" />
            <TabPane tab="Markdown" key="markdown" />
          </Tabs>
        </Form.Item>
      </Form>
    );
  }

  render() {
    const { isModalVisible, isEditing } = this.state;
    const { editingTemplate } = this.props.MessageTemplateStore;
    
    return (
      <div className="message-template-selector">
        <Button 
          type="primary" 
          onClick={this.showTemplateSelector}
          style={{ marginLeft: '10px' }}
        >
          消息选择
        </Button>
        
        <Modal
          title={isEditing ? (editingTemplate.id ? "编辑消息模板" : "新建消息模板") : "选择消息模板"}
          visible={isModalVisible}
          onCancel={this.closeTemplateSelector}
          footer={isEditing ? [
            <Button key="cancel" onClick={this.cancelEdit}>
              取消
            </Button>,
            <Button key="save" type="primary" onClick={this.saveTemplate}>
              保存
            </Button>,
          ] : [
            <Button 
              key="add" 
              type="primary" 
              icon="plus" 
              onClick={this.addNewTemplate}
            >
              新建模板
            </Button>,
            <Button key="cancel" onClick={this.closeTemplateSelector}>
              取消
            </Button>,
          ]}
          width={700}
        >
          {isEditing ? this.renderEditForm() : this.renderTemplateList()}
        </Modal>
      </div>
    );
  }
}

export default MessageTemplateSelector; 